package com.bestcem.xm.ticket.controller;

import com.bestcem.xm.component.security.annotation.AuthIgnore;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.ticket.dao.NotificationDao;
import com.bestcem.xm.ticket.entity.mongo.Notification;
import com.bestcem.xm.ticket.enums.NotificationTypeEnum;
import com.bestcem.xm.ticket.enums.ProjectStatusEnum;
import com.bestcem.xm.ticket.grpc.client.TicketBaseQdesGrpcService;
import com.bestcem.xm.ticket.grpc.client.dto.qdes.QdesDTO;
import com.bestcem.xm.ticket.task.NotificationTask;
import com.bestcem.xm.ticket.task.RspdTimerTask;
import com.bestcem.xm.ticket.util.NotificationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 测试 controller
 * TODO: 提测 or 上线 删除
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v1.0
 * @date 2021/9/16 15:23
 */
@Slf4j
@RequestMapping("/ticket/test")
@RestController
public class TicketTestController {

    @Value("${app.ticket.admin:test}")
    private String admin;

    @Resource
    private NotificationTask notificationTask;
    @Resource
    private NotificationUtil notificationUtil;
    @Resource
    private RspdTimerTask rspdTimerTask;
    @Resource
    private NotificationDao notificationDao;
    @Resource
    private TicketBaseQdesGrpcService ticketBaseQdesGrpcService;
    @Resource
    private HttpServletRequest request;

    @AuthIgnore
    @GetMapping("/calPeriodNotification")
    public void calPeriodNotification() {

        String userId = SecurityContextHolder.getUserId();
        log.error("[Ticket] 用户 {} 调用测试接口 calPeriodNotification", userId);

        if (!ObjectUtils.isEmpty(userId)) {
            notificationTask.calPeriodNotification();
        }
    }

    @AuthIgnore
    @GetMapping("/calPeriodNotificationOne/{surveyId}")
    public void calPeriodNotificationOne(@RequestParam String surveyId,
                                         @RequestParam(required = false) Boolean send) {

        String userId = SecurityContextHolder.getUserId();
        log.error("[Ticket] 用户 {} 调用测试接口 calPeriodNotificationOne {}", userId, surveyId);
        if (ObjectUtils.isEmpty(surveyId)) {
            return;
        }

        LocalDateTime now = LocalDateTime.now();
        int weekDay = now.getDayOfWeek().getValue(), day = now.getDayOfMonth();

        // 查询问卷的通知信息
        Notification notification = notificationDao.findBySurveyId(surveyId);
        if (Objects.isNull(notification)) {
            log.warn("[Ticket] calPeriodNotification notification null {}", surveyId);
            return;
        }
        if (ObjectUtils.isEmpty(notification.getSurveyId())) {
            log.warn("[Ticket] calPeriodNotification notification.getSurveyId null {}", notification.getId());
            return;
        }
        // 查询问卷信息
        QdesDTO project = ticketBaseQdesGrpcService.getQdesProject(notification.getSurveyId());
        if (Objects.isNull(project)) {
            log.warn("[Ticket] calPeriodNotification 查询问卷失败 {}", notification.getId());
            return;
        }
        if (!ProjectStatusEnum.ACTIVATED.getIndex().equals(project.getStatus())) {
            log.warn("[Ticket] calPeriodNotification 问卷关闭 {}", notification.getId());
            return;
        }
        if (Objects.isNull(notification.getRule())) {
            log.warn("[Ticket] calPeriodNotification notification.getRule null {}", notification.getId());
            return;
        }

        if (Objects.isNull(notification.getRule().getFreqEnable())) {
            notification.getRule().setFreqEnable(false);
        }
        boolean freq = false;
        // 回收频次提醒
        if (notification.getRule().getFreqEnable()) {
            String freqTime = notification.getRule().getFreqTime();
            if (NotificationTask.NOTIFICATION_TYPE_DAY.equals(freqTime)) {
                // 如果是按天提醒
                freq = true;
            } else if (NotificationTask.NOTIFICATION_TYPE_WEEK.equals(freqTime) && weekDay == 1) {
                // 如果是按周提醒 & 周一
                freq = true;
            } else if (NotificationTask.NOTIFICATION_TYPE_MONTH.equals(freqTime) && day == 1) {
                // 如果是按月提醒 & 1号
                freq = true;
            }
        }

        if (Objects.isNull(notification.getRule().getRatioEnable())) {
            notification.getRule().setRatioEnable(false);
        }
        boolean ratio = false;
        // 回收占比提醒答卷数
        if (notification.getRule().getRatioEnable()) {
            String ratioTime = notification.getRule().getRatioTime();
            if (NotificationTask.NOTIFICATION_TYPE_DAY.equals(ratioTime)) {
                // 如果是按天提醒
                ratio = true;
            } else if (NotificationTask.NOTIFICATION_TYPE_WEEK.equals(ratioTime) && weekDay == 1) {
                // 如果是按周提醒 & 周一
                ratio = true;
            } else if (NotificationTask.NOTIFICATION_TYPE_MONTH.equals(ratioTime) && day == 1) {
                // 如果是按月提醒 & 1号
                ratio = true;
            }
        }

        if (freq) {
            // 计算统计 回收频次通知提醒
            try {
                Notification res = notificationTask.calcRspdFreq(notification);
                log.warn("[Ticket] 回收频次提醒 ticketSendDTOFreq {}", res);
                if (Boolean.TRUE.equals(send) && Objects.nonNull(res)) {
                    notificationUtil.notifyHelper(res, "", NotificationTypeEnum.FREQ_RSPD.getIndex(),
                            notification.getSurveyId(), null);
                }
            } catch (Exception e) {
                log.warn("[Ticket] 回收频次提醒报错 projectId {}", notification.getSurveyId(), e);
            }
        }
        if (ratio) {
            // 计算统计 回收环比通知提醒
            try {
                Notification res = notificationTask.calcRspdRatio(notification);
                if (Boolean.TRUE.equals(send) && Objects.nonNull(res)) {
                    notificationUtil.notifyHelper(res, "", NotificationTypeEnum.RATIO_RSPD.getIndex(),
                            notification.getSurveyId(), null);
                }
                log.warn("[Ticket] 回收环比提醒 ticketSendDTORatio {}", res);
            } catch (Exception e) {
                log.warn("[Ticket] 回收占比提醒报错 projectId{}", notification.getSurveyId(), e);
            }
        }
    }

    @GetMapping("/rspdStatusTimer")
    public void rspdStatusTimer() {

        String userId = SecurityContextHolder.getUserId();
        log.error("[Ticket] 用户 {} 调用测试接口 rspdStatusTimer", userId);

        if (!ObjectUtils.isEmpty(userId) && userId.equals(admin)) {
            rspdTimerTask.rspdStatusTimer();
        }
    }

}
